package it.cinema;

import it.cinema.biz.RequestVisionBiz;

import java.io.IOException;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.codehaus.jackson.map.ObjectMapper;

public class CinemaLVisionServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(CinemaLVisionServlet.class.getName());
	private static DataSource dataSource;
	
	public void init() throws ServletException {
		log.info("Connessione al database in corso....");
		try {
			Context initContext  = new InitialContext();
			Context envContext  = (Context)initContext.lookup("java:/comp/env");
			dataSource = (DataSource)envContext.lookup("jdbc/dbcinema");
			log.info("Connessione al database effettuata correttamente!");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json");
		resp.setCharacterEncoding("UTF-8");

		log.info("richiesta da : "+ req.getRemoteHost() + " con parametri : " + req.getQueryString());
		
		String lats = (String) req.getParameter("lat");
		String lons = (String) req.getParameter("lon");
		String radiuss = (String) req.getParameter("radius");
		String alts = (String) req.getParameter("alt");
		String image = (String) req.getParameter("recognizedReferenceImage");

		float lat = 0.0f;
		float lon = 0.0f;
		try {
			lat = new Float(lats).floatValue();
			lon = new Float(lons).floatValue();
		} catch (NumberFormatException nfe) {
		}
		int alt = 5;
		if (alts != null) {
			alt = new Float(alts).intValue();
		}
		int radius = 20000;
		if (radiuss != null) {
			radius = new Integer(radiuss).intValue();
		}

		ObjectMapper mapper = new ObjectMapper();
		Response result = new Response();

		RequestVisionBiz requestBiz = new RequestVisionBiz();
		result = requestBiz.handleRequest( lat, lon, radius, alt, image);
		mapper.writeValue(resp.getWriter(), result);
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
}
